/**
 * 研发流程状态机MobX Store实现
 */
import { observable, action, computed } from 'mobx-miniprogram';
import { standardizeModuleStore } from '../../../../../../store/helpers/store_standardizer.js';
import { 
  PROJECT_STATUS, 
  PROJECT_REVIEW_SUB_STATUS,
  ACTIVE_STATE,
  DORMANT_SUB_STATUS,
  SUB_STATE,
  STATE_EVENTS,
  LEVEL1_FIELD,
  LEVEL2_FIELD,
  LEVEL3_FIELD,
  LEVEL4_FIELD
} from './constants';
import { 
  getAvailableEvents, 
  getTransitionByEvent 
} from './transitions';

// 使用统一配置入口模式导入所需模块
const { 
  cloudHelper, 
  dateHelper, 
  pageHelper,
  stateFieldHelper 
} = require('../../../../config/project_helpers_config');
const { dayjs } = require('../../../../config/libs_config');
const { BaseBiz } = require('../../../../config/biz_config');
const userBiz = require('../../../../config/passport_biz_config');

/**
 * 研发流程状态机Store类
 */
class ResearchStateMachineStore {
  constructor() {
    this.data = observable({
      // 当前项目数据
      project: null,
      
      // 当前用户角色
      currentRole: '',
      
      // 模拟的角色（用于调试）
      simulatedRole: '',
      
      // 当前状态下可用的事件
      availableEvents: [],
      
      // 资源上传状态
      resourceUploads: [],
      
      // 需要的文档
      requiredDocs: [],
      
      // 流程历史记录
      flowHistory: [],
      
      // 加载状态
      loading: {
        project: false,
        events: false,
        flowHistory: false,
        resources: false
      },
      
      // 错误状态
      error: {
        project: null,
        events: null,
        flowHistory: null,
        resources: null
      },
      
      // 状态变更详细日志
      stateChangeLog: {
        operatorInfo: null,     // 操作人详细信息
        operationDetails: [],   // 操作详情记录
        relatedDocuments: [],   // 相关文档记录
        actionTimeline: []      // 操作时间线
      }
    });
  }
  
  // 设置项目数据
  @action
  setProject(project) {
    if (!project) return;
    
    try {
      // 确保项目数据使用新字段格式
      const normalizedProject = stateFieldHelper.ensureNewFields(project);
      
      // 确保项目数据格式正确
      this.data.project = {
        ...normalizedProject,
        // 确保状态字段存在 - 使用level字段名
        [LEVEL1_FIELD]: normalizedProject[LEVEL1_FIELD] || PROJECT_STATUS.NONE,
        [LEVEL2_FIELD]: normalizedProject[LEVEL2_FIELD] || '',
        [LEVEL3_FIELD]: normalizedProject[LEVEL3_FIELD] || '',
        [LEVEL4_FIELD]: normalizedProject[LEVEL4_FIELD] || ''
      };
    } catch (e) {
      console.error('处理项目数据失败', e);
      // 基础项目数据
      this.data.project = {
        ...project,
        [LEVEL1_FIELD]: project[LEVEL1_FIELD] || PROJECT_STATUS.NONE,
        [LEVEL2_FIELD]: project[LEVEL2_FIELD] || '',
        [LEVEL3_FIELD]: project[LEVEL3_FIELD] || '',
        [LEVEL4_FIELD]: project[LEVEL4_FIELD] || ''
      };
    }
    
    // 重置错误
    this.data.error.project = null;
    
    // 加载该项目状态下可用的事件
    this.loadAvailableEvents();
  }
  
  // 设置当前角色
  @action
  setCurrentRole(role) {
    this.data.currentRole = role;
    
    // 更新可用事件
    this.loadAvailableEvents();
  }
  
  // 模拟角色（调试用）
  @action
  simulateRole(role) {
    if (!role) {
      this.data.simulatedRole = '';
      return;
    }
    
    // 验证角色是否在允许模拟的角色列表中
    const allowedRoles = [
      'admin',
      'research_manager',
      'director',
      'hardware_engineer',
      'software_engineer',
      'tester',
      'business_staff',
      'sample_team',
      'purchaser',
      'document_controller',
      'warehouse_keeper',
      'receptionist',
      'secretary',
      'production_supervisor',
      'production_engineer',
      'sample_manager'
    ];
    
    if (allowedRoles.includes(role)) {
      this.data.simulatedRole = role;
      
      // 记录模拟操作日志
      console.log(`[状态机] 模拟角色: ${role}`);
      
      // 添加到操作日志
      this._addOperationLog({
        type: 'ROLE_SIMULATION',
        content: `模拟角色: ${this.getCurrentRoleName}`,
        timestamp: dayjs().valueOf()
      });
      
      // 更新可用事件
      this.loadAvailableEvents();
    } else {
      console.error(`[状态机] 不允许模拟角色: ${role}`);
    }
  }
  
  // 获取可用的事件列表
  getAvailableEvents() {
    // 如果项目未加载或处于表单编辑模式，返回空数组
    if (!this.data.project || this.data.project.isFormMode) {
      console.log('[状态机] 项目为表单模式或新建状态，无可用事件');
      return [];
    }
    
    // 获取当前状态
    const currentLevel1 = this.data.project[LEVEL1_FIELD];
    const currentLevel3 = this.data.project[LEVEL3_FIELD];
    const currentLevel2 = this.data.project[LEVEL2_FIELD];
    const currentLevel4 = this.data.project[LEVEL4_FIELD];
    
    try {
      // 从transitions模块获取可用事件
      const events = getAvailableEvents(
        currentLevel1,
        currentLevel3,
        currentLevel1 === PROJECT_STATUS.ACTIVE ? currentLevel4 : currentLevel2,
        this.getCurrentRole
      );
      
      // 过滤出当前角色有权限执行的事件
      return Array.isArray(events) ? events : [];
    } catch (error) {
      console.error('[状态机] 获取可用事件失败:', error);
      return [];
    }
  }
  
  // 获取当前角色（实际角色或模拟角色）
  get getCurrentRole() {
    return this.data.simulatedRole || this.data.currentRole || 'visitor';
  }
  
  // 获取当前角色名称
  get getCurrentRoleName() {
    const roleMap = {
      'admin': '管理员',
      'research_manager': '研发经理',
      'director': '董事长',
      'hardware_engineer': '硬件工程师',
      'software_engineer': '软件工程师',
      'tester': '测试人员',
      'business_staff': '业务员',
      'sample_team': '样品组',
      'purchaser': '采购人员',
      'document_controller': '文控',
      'warehouse_keeper': '仓库管理员',
      'receptionist': '前台',
      'secretary': '文秘',
      'production_supervisor': '生产主管',
      'production_engineer': '生产工程师(PE)',
      'sample_manager': '样品管理员',
      'visitor': '访客'
    };
    
    return roleMap[this.getCurrentRole] || this.getCurrentRole;
  }
  
  // 获取当前状态描述
  get getCurrentStateDescription() {
    if (!this.data.project) return '未知状态';
    
    return this.getFullStatusDesc(this.data.project);
  }
  
  /**
   * 获取项目完整状态描述
   * @param {Object} project 项目数据
   * @returns {string} 状态描述文本
   */
  getFullStatusDesc(project) {
    if (!project) return '';
    
    // 确保项目使用新字段
    const normalizedProject = stateFieldHelper.ensureNewFields(project);
    
    const level1 = normalizedProject[LEVEL1_FIELD];
    const level2 = normalizedProject[LEVEL2_FIELD];
    const level3 = normalizedProject[LEVEL3_FIELD];
    const level4 = normalizedProject[LEVEL4_FIELD];
    
    let statusName = this.getStatusName(level1);
    let parts = [statusName];
    
    // 添加子状态名
    if (level2) {
      const subStatusName = this.getSubStatusName(level1, level2);
      if (subStatusName) {
        parts.push(subStatusName);
      }
    }
    
    // 添加活动状态和子状态
    if (level1 === PROJECT_STATUS.ACTIVE && level3) {
      const activeStateName = this.getActiveStateName(level3);
      if (activeStateName) {
        parts.push(activeStateName);
      }
      
      if (level4) {
        const activeSubStateName = this.getActiveSubStateName(level3, level4);
        if (activeSubStateName) {
          parts.push(activeSubStateName);
        }
      }
    }
    
    return parts.join(' > ');
  }
  
  // 获取状态名称
  getStatusName(status) {
    switch (status) {
      case PROJECT_STATUS.NONE: return '未定义';
      case PROJECT_STATUS.PROJECT_REVIEW: return '项目审核';
      case PROJECT_STATUS.DORMANT: return '休眠';
      case PROJECT_STATUS.ACTIVE: return '活动';
      case PROJECT_STATUS.COMPLETED: return '已完成';
      default: return '未知状态';
    }
  }
  
  // 获取子状态名称
  getSubStatusName(status, subStatus) {
    // 根据主状态选择子状态集合
    let subStatusSet = {};
    
    switch (status) {
      case PROJECT_STATUS.PROJECT_REVIEW:
        subStatusSet = PROJECT_REVIEW_SUB_STATUS;
        break;
      case PROJECT_STATUS.ACTIVE:
        subStatusSet = SUB_STATE;
        break;
      case PROJECT_STATUS.DORMANT:
        subStatusSet = DORMANT_SUB_STATUS;
        break;
      case PROJECT_STATUS.COMPLETED:
        return '已完成';
      default:
        return '未知子状态';
    }
    
    // 在对应子状态集合中查找名称
    for (const key in subStatusSet) {
      if (subStatusSet[key] === subStatus) {
        return key;
      }
    }
    
    return '未知子状态';
  }
  
  // 获取活动状态名称
  getActiveStateName(activeState) {
    // 从活动状态常量中获取名称
    switch (activeState) {
      case 'DESIGN': return '设计阶段';
      case 'PROTOTYPE': return '样机阶段';
      case 'TESTING': return '测试阶段';
      case 'PRODUCTION': return '生产阶段';
      default: return activeState || '未知活动状态';
    }
  }
  
  // 获取活动子状态名称
  getActiveSubStateName(activeState, activeSubState) {
    // 根据活动状态匹配子状态名称
    switch (activeState) {
      case 'DESIGN':
        switch (activeSubState) {
          case 'REQUIREMENTS_ANALYSIS': return '需求分析';
          case 'CONCEPTUAL_DESIGN': return '概念设计';
          case 'DETAILED_DESIGN': return '详细设计';
          case 'DESIGN_REVIEW': return '设计评审';
          default: return activeSubState || '未知设计子状态';
        }
      case 'PROTOTYPE':
        switch (activeSubState) {
          case 'PARTS_PROCUREMENT': return '零件采购';
          case 'ASSEMBLY': return '组装';
          case 'PROTOTYPE_REVIEW': return '样机评审';
          default: return activeSubState || '未知样机子状态';
        }
      case 'TESTING':
        switch (activeSubState) {
          case 'FUNCTION_TESTING': return '功能测试';
          case 'RELIABILITY_TESTING': return '可靠性测试';
          case 'PERFORMANCE_TESTING': return '性能测试';
          case 'TESTING_REVIEW': return '测试评审';
          default: return activeSubState || '未知测试子状态';
        }
      case 'PRODUCTION':
        switch (activeSubState) {
          case 'PRODUCTION_PLANNING': return '生产计划';
          case 'MASS_PRODUCTION': return '批量生产';
          case 'PRODUCTION_MONITORING': return '生产监控';
          default: return activeSubState || '未知生产子状态';
        }
      default:
        return activeSubState || '未知活动子状态';
    }
  }
  
  // 记录操作日志
  @action
  _addOperationLog(logData) {
    if (!this.data.stateChangeLog.operationDetails) {
      this.data.stateChangeLog.operationDetails = [];
    }
    
    this.data.stateChangeLog.operationDetails.push({
      ...logData,
      timestamp: logData.timestamp || dayjs().valueOf()
    });
  }
  
  // 检查是否可以进行状态流转
  canTransition(eventId) {
    if (!this.data.project) return false;
    if (!eventId) return false;
    
    // 检查事件是否在可用事件列表中
    return this.data.availableEvents.some(event => event.id === eventId);
  }
  
  /**
   * 执行状态转换
   * @param {Object} params 转换参数
   * @returns {Promise<Object>} 转换结果
   */
  @action
  async transition(params) {
    // 验证参数
    if (!params || !params.eventId || !this.data.project) {
      console.error('[状态机] 转换参数无效:', params);
      return { success: false, message: '转换参数无效' };
    }
    
    // 检查当前角色是否有权限执行此事件
    if (!this.canTransition(params.eventId)) {
      console.error('[状态机] 当前角色无权执行此事件:', params.eventId);
      return { success: false, message: '当前角色无权执行此事件' };
    }
    
    try {
      // 显示加载状态
      pageHelper.showLoading('执行中...');
      
      // 获取转换定义
      const transition = getTransitionByEvent(
        this.data.project[LEVEL1_FIELD],
        this.data.project[LEVEL3_FIELD],
        this.data.project[LEVEL1_FIELD] === PROJECT_STATUS.ACTIVE ? 
          this.data.project[LEVEL4_FIELD] : this.data.project[LEVEL2_FIELD],
        params.eventId
      );
      
      if (!transition) {
        pageHelper.hideLoading();
        console.error('[状态机] 找不到该事件的转换定义:', params.eventId);
        return { success: false, message: '找不到该事件的转换定义' };
      }
      
      // 准备提交云函数的数据
      const operationData = {
        projectId: this.data.project._id,
        eventId: params.eventId,
        formData: params.formData || {},
        files: params.files || [],
        comments: params.comments || '',
        fromStatus: this.data.project[LEVEL1_FIELD],
        toStatus: transition.target || this.data.project[LEVEL1_FIELD],
        fromActiveState: this.data.project[LEVEL3_FIELD],
        toActiveState: transition.activeState || this.data.project[LEVEL3_FIELD],
        operator: {
          id: userBiz.getUserId(),
          name: userBiz.getUserName(),
          role: this.getCurrentRole
        }
      };
      
      // 调用云函数执行转换
      const res = await cloudHelper.callCloudAsync('research/project_transition', operationData);
      
      if (res && res.result && res.result.success) {
        // 更新项目数据
        this.setProject(res.result.project);
        
        // 添加操作日志
        this._addOperationLog({
          type: 'STATE_TRANSITION',
          eventId: params.eventId,
          from: {
            level1: operationData.fromStatus,
            level3: operationData.fromActiveState
          },
          to: {
            level1: res.result.project[LEVEL1_FIELD],
            level3: res.result.project[LEVEL3_FIELD]
          },
          timestamp: dayjs().valueOf()
        });
        
        pageHelper.hideLoading();
        return { success: true, message: res.result.message || '操作成功', project: res.result.project };
      } else {
        pageHelper.hideLoading();
        console.error('[状态机] 转换失败:', res && res.result ? res.result.message : '未知错误');
        return { success: false, message: res && res.result ? res.result.message : '转换失败' };
      }
    } catch (error) {
      pageHelper.hideLoading();
      console.error('[状态机] 转换出错:', error);
      return { success: false, message: error.message || '操作出错' };
    }
  }
  
  /**
   * 计算项目进度百分比
   * @param {Object} project 项目数据
   * @returns {Number} 进度百分比(0-100)
   */
  calculateProgress(project) {
    if (!project) return 0;
    
    // 确保项目使用新字段
    const normalizedProject = stateFieldHelper.ensureNewFields(project);
    
    const level1 = normalizedProject[LEVEL1_FIELD];
    const level2 = normalizedProject[LEVEL2_FIELD];
    const level3 = normalizedProject[LEVEL3_FIELD];
    const level4 = normalizedProject[LEVEL4_FIELD];
    
    // 根据不同状态返回不同的进度
    if (level1 === PROJECT_STATUS.COMPLETED) return 100;
    
    // 项目审核阶段
    if (level1 === PROJECT_STATUS.PROJECT_REVIEW) {
      if (level2 === PROJECT_REVIEW_SUB_STATUS.DIRECTOR) return 5;
      if (level2 === PROJECT_REVIEW_SUB_STATUS.RD_MANAGER) return 10;
      if (level2 === PROJECT_REVIEW_SUB_STATUS.ASSIGNMENT) return 15;
      return 5; // 默认值
    }
    
    // 休眠状态
    if (level1 === PROJECT_STATUS.DORMANT) return 20;
    
    // 活动状态
    if (level1 === PROJECT_STATUS.ACTIVE) {
      if (!level3) return 20;
      
      // 硬件确认
      if (level3 === ACTIVE_STATE.HARDWARE_CONFIRM) return 25;
      
      // 硬件阶段
      if (level3 === ACTIVE_STATE.HARDWARE) {
        if (level4 === SUB_STATE.DESIGN) return 30;
        if (level4 === SUB_STATE.REVIEW) return 32;
        if (level4 === SUB_STATE.SAMPLE) return 35;
        if (level4 === SUB_STATE.PRODUCTION_SAMPLE) return 38;
        if (level4 === SUB_STATE.IN_STOCK) return 40;
        return 30; // 默认值
      }
      
      // 调试阶段
      if (level3 === ACTIVE_STATE.DEBUG) return 45;
      
      // 资料同步阶段
      if (level3 === ACTIVE_STATE.DATA_SYNC) return 50;
      
      // 测试阶段
      if (level3 === ACTIVE_STATE.TESTING) {
        if (level4 === SUB_STATE.TESTING) return 55;
        if (level4 === SUB_STATE.NO_TEST_REVIEW) return 58;
        return 55; // 默认值
      }
      
      // ... 继续保留其他状态的进度判断代码 ...
      
      return 20; // 默认值
    }
    
    return 0; // 未知状态
  }
}

// 导出标准化的Store
export default standardizeModuleStore(new ResearchStateMachineStore()); 